package com.dji.sample.configuration;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * RestTemplate配置类
 * 用于配置HTTP客户端
 */
@Configuration
public class RestTemplateConfig {

    /**
     * 配置RestTemplate Bean
     * @return RestTemplate实例
     */
    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        // 设置连接超时时间（毫秒）- 30分钟
        factory.setConnectTimeout(1800000);
        // 设置读取超时时间（毫秒）- 30分钟
        factory.setReadTimeout(1800000);

        RestTemplate restTemplate = new RestTemplate(factory);

        // 配置JSON消息转换器
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();

        // 添加Jackson JSON消息转换器
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        jsonConverter.setObjectMapper(objectMapper);

        // 将JSON转换器添加到转换器列表的开头，确保优先使用
        messageConverters.add(0, jsonConverter);

        return restTemplate;
    }
}